package com.jiantong.work.impl.manager;

import com.google.common.collect.Maps;
import com.jiantong.common.util.UserUtil;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.work.dto.ImmunizationRecordDto;
import com.jiantong.work.enums.AnimalMarkStatus;
import com.jiantong.work.enums.DocumentsDeleteFlag;
import com.jiantong.work.enums.DocumentsType;
import com.jiantong.work.impl.dao.AnimalMarkDao;
import com.jiantong.work.impl.dao.ImmunizationRecordDao;
import com.jiantong.work.impl.dao.ImmunizationSubRecordDao;
import com.jiantong.work.impl.dao.ReportHandleResumeDao;
import com.jiantong.work.model.ImmunizationRecord;
import com.jiantong.work.model.ImmunizationSubRecord;
import com.jiantong.work.model.ReportHandleResume;
import com.jiantong.work.util.Utils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by maowenjie on 2017/4/10.
 *
 */
@Component
public class ImmunizationRecordManager {
    private final ImmunizationRecordDao immunizationRecordDao;

    private final ReportHandleResumeDao reportHandleResumeDao;

    private final ImmunizationSubRecordDao immunizationSubRecordDao;

    private final AnimalMarkDao animalMarkDao;

    @Autowired
    public ImmunizationRecordManager(ImmunizationRecordDao immunizationRecordDao,
                                     ReportHandleResumeDao reportHandleResumeDao,
                                     ImmunizationSubRecordDao immunizationSubRecordDao,
                                     AnimalMarkDao animalMarkDao) {
        this.immunizationRecordDao = immunizationRecordDao;
        this.reportHandleResumeDao = reportHandleResumeDao;
        this.immunizationSubRecordDao = immunizationSubRecordDao;
        this.animalMarkDao = animalMarkDao;
    }
    /**
     * 新建防疫中心-免疫记录表
     * @param immunizationRecordDto 防疫中心-免疫记录表
     * @param toStatus 到状态
     * @return Map<String , Object>
     */
    @Transactional
    public Map<String , Object> createImmunizationRecord(ImmunizationRecordDto immunizationRecordDto, Integer toStatus){
        ImmunizationRecord immunizationRecord = immunizationRecordDto.getImmunizationRecord();
        List<Map<String , Object>> vaccines = immunizationRecordDto.getVaccines();
        Integer fromStatus = immunizationRecord.getStatus();
        ReportHandleResume reportHandleResume;
        Map<String , Object> map = Maps.newHashMap();

        LoginUser loginUser = UserUtil.getCurrentUser();
        String prefix = "FMY";
        prefix = Utils.createPrefix(prefix,loginUser);//单据编号前缀的开头字母 和 当前用户
        String number = Utils.create(prefix,immunizationRecordDao.findCurrentMaxNumber(prefix));//要在表中拿到当前最大的Number号
        immunizationRecord.setNumber(number);

        immunizationRecord.setDeleteFlag(DocumentsDeleteFlag.NORMAL.value());
        if(toStatus != null && !fromStatus.equals(toStatus)){
            immunizationRecord.setStatus(toStatus);
            immunizationRecordDao.create(immunizationRecord);
            map.put("immunizationRecordId",immunizationRecord.getId());

            reportHandleResume = new ReportHandleResume();
            reportHandleResume.setReportId(immunizationRecord.getId());
            reportHandleResume.setReportNumber(immunizationRecord.getNumber());
            reportHandleResume.setType(DocumentsType.IMMUNIZATION_RECORDMANAGER.value());
            reportHandleResume.setFromStatus(fromStatus);
            reportHandleResume.setToStatus(toStatus);
            reportHandleResume.setUserId(loginUser.getId());
            reportHandleResume.setUserName(loginUser.getName());
            reportHandleResumeDao.create(reportHandleResume);
            map.put("reportHandleResumeId",reportHandleResume.getId());

        }else {
            immunizationRecordDao.create(immunizationRecord);
            map.put("immunizationRecordId",immunizationRecord.getId());
        }
        List<String> currentMarkNumbers = immunizationRecord.getEarNumbers();
        if(currentMarkNumbers != null && !currentMarkNumbers.isEmpty()){
            Map<String , Object> map1 = Maps.newHashMap();
            map1.put("markNumbers",immunizationRecord.getEarNumbers());
            map1.put("breedStableId",immunizationRecord.getStableId());
            map1.put("breedStableNumber",immunizationRecord.getStableNumber());
            map1.put("status", AnimalMarkStatus.USE.value());
            map1.put("woreAt",new Date());
            animalMarkDao.updateMarks(map1);
        }
        //处理字表的信息 创建
        if(vaccines != null && !vaccines.isEmpty()){
            ImmunizationSubRecord immunizationSubRecord = buildImmunizationSubRecord(vaccines,immunizationRecord.getId());
            if(immunizationSubRecord != null){
                immunizationSubRecordDao.create(immunizationSubRecord);
            }
        }
        return map;
    }


    /**
     * 更新防疫中心--免疫记录表
     * @param immunizationRecordDto 防疫中心-免疫记录表
     * @param toStatus 到状态
     * @return Map<String , Object>
     */
    @Transactional
    public Map<String , Object> updateImmunizationRecord(ImmunizationRecordDto immunizationRecordDto,Integer toStatus){
        ImmunizationRecord immunizationRecord = immunizationRecordDto.getImmunizationRecord();
        List<Map<String , Object>> vaccines = immunizationRecordDto.getVaccines();
        List<String> originalEar = immunizationRecordDto.getOriginalEar();
        List<String> currentEar = immunizationRecord.getEarNumbers();
        Integer fromStatus = immunizationRecord.getStatus();
        ReportHandleResume reportHandleResume;
        Boolean flagImmunizationRecord;
        Map<String , Object> map = Maps.newHashMap();
        if(toStatus != null && !fromStatus.equals(toStatus)){
            immunizationRecord.setStatus(toStatus);
            flagImmunizationRecord = immunizationRecordDao.update(immunizationRecord);
            map.put("flagImmunizationRecord",flagImmunizationRecord);

            reportHandleResume = new ReportHandleResume();
            reportHandleResume.setReportId(immunizationRecord.getId());
            reportHandleResume.setReportNumber(immunizationRecord.getNumber());
            reportHandleResume.setType(DocumentsType.IMMUNIZATION_RECORDMANAGER.value());
            reportHandleResume.setFromStatus(fromStatus);
            reportHandleResume.setToStatus(toStatus);
            reportHandleResume.setUserId(UserUtil.getCurrentUser().getId());
            reportHandleResume.setUserName(UserUtil.getCurrentUser().getName());
            reportHandleResumeDao.create(reportHandleResume);
            map.put("reportHandleResumeId",reportHandleResume.getId());

        }else {
            flagImmunizationRecord = immunizationRecordDao.update(immunizationRecord);
            map.put("flagImmunizationRecord",flagImmunizationRecord);
        }

        if(originalEar != null && !originalEar.isEmpty()){
            Map<String , Object> map1 = Maps.newHashMap();
            map1.put("markNumbers",originalEar);
            map1.put("breedStableId",immunizationRecord.getStableId());
            map1.put("breedStableNumber",immunizationRecord.getStableNumber());
            map1.put("status", AnimalMarkStatus.DEPOSITED.value());
            map1.put("woreAt",null);
            animalMarkDao.updateMarks(map1);
        }

        if(currentEar != null && !currentEar.isEmpty()){
            Map<String , Object> map1 = Maps.newHashMap();
            map1.put("markNumbers",currentEar);
            map1.put("breedStableId",null);
            map1.put("breedStableNumber",null);
            map1.put("status", AnimalMarkStatus.USE.value());
            map1.put("woreAt",immunizationRecord.getCreatedAt());
            animalMarkDao.updateMarks(map1);
        }
        if(vaccines != null && !vaccines.isEmpty()){
            updateImmunizationSubRecord(vaccines);
            ImmunizationSubRecord immunizationSubRecord = buildImmunizationSubRecord(vaccines,immunizationRecord.getId());
            if(immunizationSubRecord != null){
                immunizationSubRecordDao.create(immunizationSubRecord);
            }
        }

        return map;
    }



    private ImmunizationSubRecord buildImmunizationSubRecord(List<Map<String, Object>> vaccines,Long vaccineId) {

        ImmunizationSubRecord immunizationSubRecord = null;
        for(Map<String , Object> map : vaccines){
            if(map.getOrDefault("id",null)== null){
                immunizationSubRecord = new ImmunizationSubRecord();
                immunizationSubRecord.setVaccineId(vaccineId);
                Object object2 = map.getOrDefault("stableId",null);
                Long stableId = (object2 != null ? Long.valueOf((int)object2):null);
                immunizationSubRecord.setStableId(stableId);
                immunizationSubRecord.setStableNumber((String) map.getOrDefault("stableNumber",null));
                immunizationSubRecord.setArea((Integer) map.getOrDefault("area",null));
                immunizationSubRecord.setBatch((Map<String, Map<String, String>>) map.getOrDefault("batch",null));
                immunizationSubRecord.setManufacturer((Map<String, Map<String, String>>) map.getOrDefault("manufacturer",null));
                Object object = map.getOrDefault("date",new Date());
                Date date = null;
                if(object instanceof Long) date = new Date((long)object);
                else if(object instanceof String) date = DateTime.parse((String)object).toDate();
                else if(object instanceof char[]) date = DateTime.parse((String)object).toDate();
                immunizationSubRecord.setDate(date);
                immunizationSubRecord.setDays((Integer) map.getOrDefault("days",0));
                immunizationSubRecord.setTimes((Integer) map.getOrDefault("times",0));
                immunizationSubRecord.setType((Integer) map.getOrDefault("type",null));
                immunizationSubRecord.setOperatorName((String) map.getOrDefault("operatorName",null));
                immunizationSubRecord.setOtherType((String) map.getOrDefault("otherType",null));
                immunizationSubRecord.setVaccineCode((Integer) map.getOrDefault("vaccineCode",null));
                immunizationSubRecord.setVaccineName((String) map.getOrDefault("vaccineName",null));
                immunizationSubRecord.setQuantity((Integer) map.getOrDefault("quantity",0));
                Object object1 = map.getOrDefault("drugQuantity", 0f);
                Float drugQuantity = null;
                if(object1 instanceof  Integer) drugQuantity = ((Integer)object1).floatValue();
                if(object1 instanceof Double) drugQuantity = ((Double)object1).floatValue();
                immunizationSubRecord.setDrugQuantity(drugQuantity);
                immunizationSubRecord.setDrugUnit((Integer) map.getOrDefault("drugUnit",null));
                immunizationSubRecord.setMethod((Integer) map.getOrDefault("method",null));
                immunizationSubRecord.setDeleteFlag(DocumentsDeleteFlag.NORMAL.value());
                break;
            }
        }
        return immunizationSubRecord;
    }

    private void updateImmunizationSubRecord(List<Map<String, Object>> vaccines){
        ImmunizationSubRecord immunizationSubRecord = null;
        for(Map<String , Object> map : vaccines){
            if(map.getOrDefault("id",null) != null){
                immunizationSubRecord = new ImmunizationSubRecord();
                immunizationSubRecord.setId(((Integer) map.get("id")).longValue());
                immunizationSubRecord.setVaccineId(((Integer) map.getOrDefault("vaccineId",null)).longValue());
                Object object2 = map.getOrDefault("stableId",null);
                Long stableId = (object2 != null ? Long.valueOf((int)object2):null);
                immunizationSubRecord.setStableId(stableId);
                immunizationSubRecord.setStableNumber((String) map.getOrDefault("stableNumber",null));
                immunizationSubRecord.setArea((Integer) map.getOrDefault("area",null));
                immunizationSubRecord.setBatch((Map<String, Map<String, String>>) map.getOrDefault("batch",null));
                immunizationSubRecord.setManufacturer((Map<String, Map<String, String>>) map.getOrDefault("manufacturer",null));
                Object object = map.getOrDefault("date",new Date());
                Date date = null;
                if(object instanceof Long) date = new Date((long)object);
                else if(object instanceof String) date = DateTime.parse((String)object).toDate();
                else if(object instanceof char[]) date = DateTime.parse((String)object).toDate();
                immunizationSubRecord.setDate(date);
                immunizationSubRecord.setDays((Integer) map.getOrDefault("days",0));
                immunizationSubRecord.setTimes((Integer) map.getOrDefault("times",0));
                immunizationSubRecord.setType((Integer) map.getOrDefault("type",null));
                immunizationSubRecord.setOperatorName((String) map.getOrDefault("operatorName",null));
                immunizationSubRecord.setVaccineCode((Integer) map.getOrDefault("vaccineCode",null));
                immunizationSubRecord.setVaccineName((String) map.getOrDefault("vaccineName",null));
                immunizationSubRecord.setOtherType((String) map.getOrDefault("otherType",null));
                immunizationSubRecord.setQuantity((Integer) map.getOrDefault("quantity",0));
                immunizationSubRecord.setDrugUnit((Integer) map.getOrDefault("drugUnit",null ));
                Object object1 = map.getOrDefault("drugQuantity",0);
                Float drugQuantity = null;
                if(object1 instanceof  Integer) drugQuantity = ((Integer)object1).floatValue();
                if(object1 instanceof Double) drugQuantity = ((Double)object1).floatValue();
                immunizationSubRecord.setDrugQuantity(drugQuantity);
                immunizationSubRecord.setMethod((Integer) map.getOrDefault("method",null));
                immunizationSubRecord.setDeleteFlag(DocumentsDeleteFlag.NORMAL.value());
                immunizationSubRecordDao.update(immunizationSubRecord);
            }
        }
    }
}
